package com.tich.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tich.blog.domain.dto.FavoriteBlogDTO;
import com.tich.blog.domain.entity.Blog;
import com.tich.blog.domain.entity.FavoriteBlog;
import com.tich.blog.domain.vo.BlogRecommendVO;
import com.tich.blog.domain.vo.FavoriteCursorVO;
import com.tich.blog.mapper.FavoriteBlogMapper;
import com.tich.blog.service.IFavoriteBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tich.constant.SQLConstant;
import com.tich.context.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 博客收藏表 服务实现类
 * </p>
 *
 * @author 王志宇
 * @since 2025-05-25
 */

@Service
public class FavoriteBlogServiceImpl extends ServiceImpl<FavoriteBlogMapper, FavoriteBlog> implements IFavoriteBlogService {


    @Autowired
    private FavoriteBlogMapper favoriteBlogMapper;
    /**
     * 收藏帖子
     * @param blogId
     * @return
     */
    @Override
    public void insert(Long blogId) {
        Long userId = UserContext.getCurrentId();

        // 1. 检查是否已收藏
        boolean exists = query().lambda()
                .eq(FavoriteBlog::getBlogId, blogId)
                .eq(FavoriteBlog::getUserId, userId)
                .exists(); // 使用 exists() 方法优化查询

        if (exists) {
            remove(new LambdaQueryWrapper<FavoriteBlog>()
                    .eq(FavoriteBlog::getBlogId, blogId)
                    .eq(FavoriteBlog::getUserId, userId));
            return;
        }

        // 2. 创建收藏记录
        FavoriteBlog favoriteBlog = FavoriteBlog.builder()
                .blogId(blogId)
                .userId(UserContext.getCurrentId())
                .createTime(LocalDateTime.now())
                .build();

        // 3. 保存到数据库
        save(favoriteBlog);

        //TODO 帖子收藏数加一
    }

    /**
     * @param favoriteBlogDTO
     * @return
     */
    @Override
    public FavoriteCursorVO getFavoriteBlogIds(FavoriteBlogDTO favoriteBlogDTO) {
        LambdaQueryWrapper<FavoriteBlog> queryWrapper = Wrappers.lambdaQuery(FavoriteBlog.class);
        queryWrapper.eq(FavoriteBlog::getUserId, favoriteBlogDTO.getUserId());

        if (favoriteBlogDTO.getCursor() != null) {
            queryWrapper.lt(FavoriteBlog::getCreateTime, favoriteBlogDTO.getCursor());
        }

        queryWrapper.orderByDesc(FavoriteBlog::getCreateTime)
                .last(SQLConstant.LIMIT + favoriteBlogDTO.getCount());

        // 直接查询完整实体列表
        List<FavoriteBlog> favoriteBlogs = favoriteBlogMapper.selectList(queryWrapper);

        // 处理空结果
        if (favoriteBlogs.isEmpty()) {
            return FavoriteCursorVO.builder()
                    .ids(Collections.emptyList())
                    .cursor(null)
                    .build();
        }

        // 提取ID列表
        List<Long> blogIds = new ArrayList<>(favoriteBlogs.size());
        for (FavoriteBlog fav : favoriteBlogs) {
            blogIds.add(fav.getBlogId());
        }

        // 取最后一条记录的时间作为游标（因为是倒序排列）
        LocalDateTime cursor = favoriteBlogs.get(favoriteBlogs.size() - 1).getCreateTime();

        return FavoriteCursorVO.builder()
                .ids(blogIds)
                .cursor(cursor)
                .build();
    }
}
